package cn.hxsteel.storage.core.tool;

import org.apache.commons.lang.math.NumberUtils;

import cn.hxsteel.jtool.util.NumberUtil;

/**
 * 单据生成工具
 */
public class SheetTool
{
    public static final String  WIN              = "WIN";
    public static final String  OUT              = "OUT";
    
    private static final String CODE             = "0001010001";
    private static final String DEFAULT_WIN_CODE = WIN + CODE;
    private static final String DEFAULT_OUT_CODE = OUT + CODE;
    
    /** 单据后四位数字编号，同天累加，非同天清零 */
    private static int          winSerial;
    private static int          outSerial;
    /** 参考时间，和数据库最新一条数据的日期比较用 */
    private static long         refDate;
    /** 单据类型 */
    private static String       codeType;
    
    /**
     * 创建入库单号
     * 
     * @param createDate 单据创建日期，格式：两位年+月+日：120103
     * @param lastRecordCode 最新一条记录的完整单据编号
     */
    public static String createWinCode( String createDate, String lastRecordCode )
    {
	winSerial = createSerial( createDate, lastRecordCode, DEFAULT_WIN_CODE );
	return createCode( winSerial );
    }
    
    /**
     * 创建入库单号
     * 
     * @param createDate 单据创建日期，格式：两位年+月+日：120103
     * @param lastRecordCode 最新一条记录的完整单据编号
     */
    public static String createOutCode( String createDate, String lastRecordCode )
    {
	outSerial = createSerial( createDate, lastRecordCode, DEFAULT_OUT_CODE );
	return createCode( outSerial );
    }
    
    /**
     * 生成单据序号
     * 
     * @param createDate 单据创建日期，格式：两位年+月+日：120103
     * @param lastRecordCode 最新一条记录的完整单据编号
     * @param defaultCode 单据默认编号
     */
    private static int createSerial( String createDate, String lastRecordCode, String defaultCode )
    {
	int serial = 0;
	if ( lastRecordCode.equals( "" ) ) lastRecordCode = defaultCode;
	// 将给定日期和本系统编号中的日期部分转换成long类型进行比较
	long date = NumberUtils.toLong( createDate );
	refDate = NumberUtils.toLong( lastRecordCode.substring( 3, 9 ) );
	codeType = lastRecordCode.substring( 0, 3 );
	
	if ( date != refDate )
	{
	    refDate = date;
	}
	else
	{
	    serial = NumberUtils.toInt( lastRecordCode.substring( 9 ) );
	}
	serial++;
	
	return serial;
    }
    
    /**
     * 生成单据编号
     * 
     * @param serial 序号
     */
    private static String createCode( int serial )
    {
	return codeType + refDate + radixComplement( serial );
    }
    
    /**
     * 将序号补码成四位
     */
    public static String radixComplement( int serial )
    {
	return NumberUtil.radixComplement( serial, "0000" );
    }
    
}
